import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import '../l10n/app_localizations.dart';
import '../route/router.dart';
import '../route/routes.dart';
import '../theme/app_theme.dart';
import 'app_services.dart';

class App extends StatelessWidget {
  final GlobalKey<NavigatorState> navigatorKey;
  const App({super.key, required this.navigatorKey});

  @override
  Widget build(BuildContext context) {
    // 使用 AnimatedBuilder 监听 AppSettings 的变化
    return AnimatedBuilder(
      animation: AppServices.appSettings, // 监听的对象
      builder: (context, child) {
        // 当 AppServices.appSettings.notifyListeners() 被调用时，
        // 这个 builder 会被重新执行，从而更新 MaterialApp 的属性
        return MaterialApp(
          navigatorKey: navigatorKey,
          // 使用国际化文本
          onGenerateTitle: (context) {
            // 确保在 MaterialApp 构建后获取 Localizations
            return AppLocalizations.of(context)?.appTitle ?? 'Flutter Design';
          },
          // 关联主题
          theme: AppTheme.lightTheme,
          darkTheme: AppTheme.darkTheme,
          themeMode: AppServices.appSettings.themeMode, // 从 AppSettings 获取主题模式

          // 关联国际化
          locale: AppServices.appSettings.locale, // 从 AppSettings 获取语言
          localizationsDelegates: const [
            AppLocalizations.delegate, // 我们自己的 Delegate
            GlobalMaterialLocalizations.delegate, // Flutter 控件（如 TextField 的“复制”、“粘贴”菜单，或日期选择器）自身文本国际化的
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: const [
            Locale('en', ''), // English
            Locale('zh', ''), // Chinese
          ],

          // 路由保持不变
          initialRoute: Routes.home,
          onGenerateRoute: AppRouter.generateRoute,
          onUnknownRoute: AppRouter.unknownRoute,
        );
      },
    );
  }
}
